package main

import (
	"fmt"
	"os"
	"pkg.deepin.io/lib/mime"
)

func printHelper() {
	fmt.Println("Usage: mime-tools [option] [args]")
	fmt.Println("\nOption:")
	fmt.Println("\tset: using the special app to open the mime file.")
	fmt.Println("\tExample: mime-tools set text/plain gvim.desktop\n")
	fmt.Println("\tget: get the default app for the special mime")
	fmt.Println("\tExample: mime-tools get text/plain\n")
	fmt.Println("\tlist: list the apps that supported the special mime.")
	fmt.Println("\tExample: mime-tools list text/plain\n")
	fmt.Println("\tconfig: accroding the config to set default app")
	fmt.Println("\tExample: mime-tools config data.json")
	fmt.Println("\t\tdata.json:")
	fmt.Println("\t\t{")
	fmt.Println("\t\t\t\"DefaultApps\":[")
	fmt.Println("\t\t\t\t{")
	fmt.Println("\t\t\t\t\t\"AppId\": \"gvim.desktop\",")
	fmt.Println("\t\t\t\t\t\"AppType\":\"editor\",")
	fmt.Println("\t\t\t\t\t\"SupportedType\": [")
	fmt.Println("\t\t\t\t\t\t\"text/plain\"")
	fmt.Println("\t\t\t\t\t]")
	fmt.Println("\t\t\t\t}")
	fmt.Println("\t\t\t]")
	fmt.Println("\t\t}")
}

func parseArgs(args []string) {
	var err error
	switch args[0] {
	case "set":
		if len(args) != 3 {
			fmt.Println("Invalid arguments")
			return
		}
		err = mime.SetDefaultApp(args[1], args[2])
	case "get":
		if len(args) != 2 {
			fmt.Println("Invalid arguments")
			return
		}
		var app string
		app, err = mime.GetDefaultApp(args[1], false)
		if err == nil {
			fmt.Println("Default app:", app)
		}
	case "list":
		if len(args) != 2 {
			fmt.Println("Invalid arguments")
			return
		}
		apps := mime.GetAppList(args[1])
		fmt.Println("App list:", apps)
	case "config":
		if len(args) != 2 {
			fmt.Println("Invalid arguments")
			return
		}
		err = setMimeByConfig(args[1])
	default:
		fmt.Println("Invalid option:", args[0])
		return
	}

	if err != nil {
		fmt.Println("Error:", err)
	}
}

func setMimeByConfig(config string) error {
	table, err := unmarshal(config)
	if err != nil {
		fmt.Println("Unmarshal failed:", err)
		return err
	}

	for _, info := range table.Apps {
		for _, ty := range info.Types {
			mime.SetDefaultApp(ty, info.AppId)
		}
	}
	return nil
}

func main() {
	if len(os.Args) < 3 {
		printHelper()
		return
	}

	parseArgs(os.Args[1:])
	return
}
